#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);

    connect(ui->cbApple, &QCheckBox::stateChanged, this, &Widget::onStateChanged);
    connect(ui->cbPear, &QCheckBox::stateChanged, this, &Widget::onStateChanged);
    connect(ui->cbPeach, &QCheckBox::stateChanged, this, &Widget::onStateChanged);
    connect(ui->cbOrange, &QCheckBox::stateChanged, this, &Widget::onStateChanged);
    connect(ui->cbBanana, &QCheckBox::stateChanged, this, &Widget::onStateChanged);
}

Widget::~Widget()
{
    delete ui;
}

/**
 * 设置水果的选中状态
 * @brief setFruitState
 * @param state
 */
void Widget::setFruitState(bool state)
{
    ui->cbApple->setChecked(state);
    ui->cbPear->setChecked(state);
    ui->cbPeach->setChecked(state);
    ui->cbOrange->setChecked(state);
    ui->cbBanana->setChecked(state);
}

/** 单个水果的点击
 * @brief Widget::onStateChanged
 */
void Widget::onStateChanged()
{
    bool appleChecked = ui->cbApple->isChecked();
    bool pearChecked = ui->cbPear->isChecked();
    bool peachChecked = ui->cbPeach->isChecked();
    bool orangeChecked = ui->cbOrange->isChecked();
    bool bananaChecked = ui->cbBanana->isChecked();

    if(appleChecked && pearChecked && peachChecked && orangeChecked && bananaChecked) {
        // 全部选中
        ui->cbAll->setCheckState(Qt::Checked);
    } if(!(appleChecked || pearChecked || peachChecked || orangeChecked || bananaChecked)) {
        // 全部未选中
        ui->cbAll->setCheckState(Qt::Unchecked);
    } else {
        // 部分选中
        ui->cbAll->setCheckState(Qt::PartiallyChecked);
    }

    QString str;

    if(appleChecked) {
        str = str + ui->cbApple->text();
    }

    if(pearChecked) {
        str = str + ui->cbPear->text();
    }

    if(peachChecked) {
        str = str + ui->cbPeach->text();
    }

    if(orangeChecked) {
        str = str + ui->cbOrange->text();
    }

    if(bananaChecked) {
        str = str + ui->cbBanana->text();
    }

    ui->leResult->setText(str);

}

/** 全部的点击
 * @brief Widget::on_cbAll_clicked
 */
void Widget::on_cbAll_clicked()
{
    ui->cbAll->setTristate(false);

    int state = ui->cbAll->checkState();
    switch (state) {
    case Qt::Checked: // 全选
        setFruitState(true);
        break;
    case Qt::Unchecked: // 未选
        setFruitState(false);
        break;
    default:
        break;
    }
}

